package tech.wangpai.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import tech.wangpai.domain.User;

import java.util.List;

@Repository
public class UserMapper {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<User> queryUserByUsername(String username){
        String sql = " SELECT user_id,username,password,age,score FROM sys_user WHERE username = ?";
        return jdbcTemplate.query(sql,new Object[]{username},new BeanPropertyRowMapper<User>(User.class));
    }

    public User getUserById(String userId){
        String sql = "SELECT user_id,username,password,age,score FROM sys_user WHERE user_id = ?";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
        return jdbcTemplate.queryForObject(sql, rowMapper, userId);
    }

    public void addUser(User user) {
        String sql = "INSERT INTO sys_user (user_id,username,password,age,score) values(?,?,?,?,?)";
        jdbcTemplate.update(sql,user.getUserId(),user.getUsername(),user.getPassword(),user.getAge(),user.getScore());
    }

    public void delUserById(String userId){
        String sql = "DELETE FROM sys_user WHERE user_id=?";
        jdbcTemplate.update(sql,userId);
    }

    public void updateUserById(String userId, User user){
        String sql = "UPDATE sys_user SET username = ?,password=?,age=?,score=? WHERE user_id=?";
        jdbcTemplate.update(sql,user.getUsername(),user.getPassword(),user.getAge(),user.getScore(),user.getUserId());
    }

    public void updateUserAgeById(String userId, Integer age){
        String sql = "UPDATE sys_user SET age=? WHERE user_id=?";
        jdbcTemplate.update(sql,age,userId);
    }
}
